package com.zhxy.gps.alone;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhxy.gis.Location;
import com.zhxy.gps.terminal.AbstractGatewayConnector;
import com.zhxy.gps.terminal.message.LocateMessage;
import com.zhxy.gps.terminal.message.LocationMessage;
import com.zhxy.gps.terminal.message.ReplyMessage;
import com.zhxy.util.async.ResultHandler;
import com.zhxy.util.message.DuplexMessagePipe;

public class VirtualSmartphone extends AbstractGatewayConnector {
	
	private static final Logger logger = LoggerFactory.getLogger(VirtualSmartphone.class);
	
	private ScheduledFuture<?> scheduledFuture;
	
	/** 上报位置间隔 */
	private long interval;
	
	/** 开始位置 */
	private Location location;
	
	/** 开始时间 */
	private long startTime = System.currentTimeMillis();
	
	/** 速度 */
	private double speed = 0.0001;
	
	/** 方向,单位弧度 */
	private double direction = 0;

	public VirtualSmartphone() {
	}


	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}
	
	public void setInterval(long interval) {
		this.interval = interval;
	}
	
	@Override
	public void connected(DuplexMessagePipe pipe) {
		
		super.connected(pipe);
		
		if (interval != 0) {
			scheduledFuture = getExecutorService().scheduleAtFixedRate(new Runnable() {
				@Override
				public void run() {
					try {
						onTime();
					} catch (Exception e) {
						logger.error("执行定时上位置时失败", e);
					}
				}
			}, 0, interval, TimeUnit.MILLISECONDS);
		}
	}

	@Override
	public void disconnected(DuplexMessagePipe pipe) {
		super.disconnected(pipe);
		if (scheduledFuture != null) {
			scheduledFuture.cancel(false);
			scheduledFuture = null;
		}
	}


	@Override
	public void process(DuplexMessagePipe pipe, Object message,
			ResultHandler<Object> handler) {
		
		logger.debug("虚拟终端接收到指令" + message);
		if (message instanceof LocateMessage) {
			pipe.send(locate(System.currentTimeMillis() - startTime));
		}
		
		if (handler != null) {
			handler.result(new ReplyMessage(true));
		}
	}
	
	protected void onTime() {
		long now = System.currentTimeMillis();
		sendMessage(locate(now - startTime));
	}
	
	protected LocationMessage locate(long duration) {
		// 位移
		double s = speed * duration / 1000;
		double longitude = location.getLongitude() + s * Math.cos(direction);
		double latitude = location.getLatitude() + s * Math.sin(direction);
		return new LocationMessage(new Location(latitude, longitude));
	}
}
